package com.kaiyidiannao.activity.auction;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.InputFilter;
import android.text.method.DigitsKeyListener;
import android.view.View;
import android.widget.*;
import com.kaiyi.diannao.net.AsyncHttpResponseParse;
import com.kaiyi.diannao.net.LoadDataHandler;
import com.kaiyi.diannao.net.RequestClient;
import com.kaiyidiannao.adapter.CommonViewpagerAdapter;
import com.kaiyidiannao.common.BaseActionBarActivity;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.https.HttpUtils;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.AuctionDetail;
import com.kaiyidiannao.model.req.model.GetAuctionShow;
import com.kaiyidiannao.model.req.model.PostAddFavorites;
import com.kaiyidiannao.model.req.model.PostPraise;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.umeng.common.Log;

import java.math.BigDecimal;
import java.util.*;

/**
 * 拍拍乐详情界面
 *
 * @author kTian
 */
public class AuctionDetailActivity extends BaseActionBarActivity implements View.OnClickListener, Observer {

    private static final String TAG = "AuctionDetailActivity";

    private ImageView mImgPatDetaillBack;
    private TextView mTxtPatDetaillAdd;
    private ImageButton mImgButDetailRefresh;

    private TextView mTxtPricePatDetaill;
    private TextView mTxtMinPricePatDetail;
    private TextView details_money_integer; //商品价格整数部分
    private TextView details_money_decimal; //商品价格小数部分,要带个前面小数点

    private TextView mTxtTitle;
    private TextView mTxtPrivcePeople;
    private TextView mTxtPrivceTimes;
    private TextView mTxtPeopleCount;
    private TextView mTxtTime;
    private TextView mTxtPatDetaiContent;

    private ImageLoader imageLoader;

    private String mItemId;
    private String catid;

    private AuctionDetail mAuctionDetail;

    //    private ImageView mImgLoveBtn;
    private ImageView collect; //商品收藏按钮
    private View priase; //点赞
    private boolean collectFlag, priaseFlag;
    private Timer timer = new Timer();
    private boolean isFirst = true;
   private boolean isFresh = true; //是否刷新界面

    private String userid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_autiondetail);
        // 添加观察者
        DataCenter.getInstance().addObserver(this);
        Intent intent = getIntent();
        mItemId = intent.getStringExtra("itemid");

        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(AuctionDetailActivity.this));

        findView();
        initLinstener();

        getNetData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //删除观察者
        DataCenter.getInstance().deleteObserver(this);
    }

    private void findView() {
        mImgPatDetaillBack = (ImageView) findViewById(R.id.img_pat_detaill_back);
        mTxtPatDetaillAdd = (TextView) findViewById(R.id.txt_pat_detaill_add);
        mImgButDetailRefresh = (ImageButton) findViewById(R.id.txt_pat_detaill_refresh);
        details_money_integer = (TextView) findViewById(R.id.auction_details_money_integer);
        details_money_decimal = (TextView) findViewById(R.id.auction_details_money_decimal);
        mTxtMinPricePatDetail = (TextView) findViewById(R.id.txt_min_price_pat_detail);
        priase = findViewById(R.id.daydaycoupon_product_fav);
        collect = (ImageView) findViewById(R.id.daydaycoupon_product_favorite);
        mTxtTitle = (TextView) findViewById(R.id.txt_title);
        mTxtPrivcePeople = (TextView) findViewById(R.id.txt_privce_people);
        mTxtPrivceTimes = (TextView) findViewById(R.id.txt_privce_times);
        mTxtPeopleCount = (TextView) findViewById(R.id.txt_people_count);
        mTxtTime = (TextView) findViewById(R.id.txt_time);
        mTxtPatDetaiContent = (TextView) findViewById(R.id.txt_pat_detail_content);

        //八张详情图片
        detailViewPager = (ViewPager) findViewById(R.id.detail_ViewPager);
    }

    /**
     * 初始化8张详情图片
     */
    private ViewPager detailViewPager;
    private CommonViewpagerAdapter commonViewpagerAdapter;
    private List<View> imageList = new ArrayList<View>();
    private List<String> imageUrlList = new ArrayList<String>();

    private void initViewPage() {

        commonViewpagerAdapter = new CommonViewpagerAdapter(AuctionDetailActivity.this, imageList, detailViewPager, imageUrlList);

        for (int i = 0; i < imageUrlList.size(); i++) {
            final int position = i;
            ImageView imageView = (ImageView) getLayoutInflater().inflate(R.layout.common_viewpager_item, null);
            imageLoader.displayImage(imageUrlList.get(i), imageView, super.options, null);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AuctionDetailActivity.super.startImagePagerActivity(position, mAuctionDetail.getPicture());
                }
            });
            imageList.add(imageView);
        }

        detailViewPager.setAdapter(commonViewpagerAdapter);
    }

    /**
     * 显示重新加载页面
     */
    private void showReloadView() {
        showToast(getString(R.string.no_network));
        findViewById(R.id.scrollview_wrapping).setVisibility(View.GONE);
        findViewById(R.id.realod_layout).setVisibility(View.VISIBLE);
        findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findViewById(R.id.scrollview_wrapping).setVisibility(View.INVISIBLE);
                findViewById(R.id.realod_layout).setVisibility(View.GONE);
                getNetData();
            }
        });
    }

    private void initLinstener() {
        // 返回
        mImgPatDetaillBack.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        });
        // 刷新
        mImgButDetailRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 刷新界面
                if (HttpUtils.isConnected()) {
                    isFresh = true;
                    getNetData();
                } else {
                    showToast(getText(R.string.no_network).toString());
                }

            }
        });
        // 加价
        mTxtPatDetaillAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!HttpUtils.isConnected()) {
                    showToast(getText(R.string.no_network).toString());
                    return;
                }
                android.util.Log.d("currprice",mAuctionDetail.getCurrprice()+"++++");

                if (!isEnd()) { //竞拍没有结束
                    final EditText inputServer = new EditText(AuctionDetailActivity.this);
                    inputServer.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)}); //长度限制20位
                    DigitsKeyListener numericOnlyListener = new DigitsKeyListener(false, false);
                    inputServer.setKeyListener(numericOnlyListener);
                    AlertDialog.Builder builder = new AlertDialog.Builder(AuctionDetailActivity.this);
                    builder.setTitle("加价额:").setIcon(android.R.drawable.ic_dialog_info).setView(inputServer)
                            .setNegativeButton("取消", null);
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            float add = 0;
                            try {
                                if (inputServer.getText().toString() != null && !inputServer.getText().toString().equals("")) {
                                    add = Float.parseFloat(inputServer.getText().toString());
                                } else {
                                    showToast("输入不能为空");
                                    return;
                                }
                            } catch (NumberFormatException e) {
                                showToast("您输入的加码非法");
                                return;
                            }
                            float currprice = Float.parseFloat(mAuctionDetail.getCurrprice());


                            if (!isLogin()) {
                                finish();
                                startLoginOrRegistered();
                                return;
                            }

                            RequestParams params = new RequestParams();
                            params.put("userid", DataCenter.userLogin.get(0).getUserid());
                            params.put("itemid", mItemId);
                            userid = DataCenter.userLogin.get(0).getUserid();
                            if (add > 1) {

                                BigDecimal b = new BigDecimal(add);
                                float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                                Log.d("log_ktian", "" + f1 + "");
                                params.put("addprice", f1 + "");
                            } else {
                               // Toast.makeText(AuctionDetailActivity.this, DataCenter.msg, Toast.LENGTH_SHORT).show();
                            }

                                RequestClient.post(AuctionDetailActivity.this, "http://www.3tixa.com:8086/kaiyi/group/auction.php", params, new AsyncHttpResponseParse(AuctionDetailActivity.this, new LoadDataHandler() {

                                    @Override
                                    public void onStart() {
                                        showProgressDialog();
                                    }

                                    @Override
                                    public void onSuccess(String data) {
                                        // 刷新界面
                                        getNetData();
                                    }

                                    @Override
                                    public void onFinish() {
                                        if(DataCenter.msg.equals("")){
                                            Toast.makeText(AuctionDetailActivity.this,"请求失败,请重试", Toast.LENGTH_SHORT).show();
                                        }else {
                                            Toast.makeText(AuctionDetailActivity.this,DataCenter.msg, Toast.LENGTH_SHORT).show();
                                        }
                                        DataCenter.msg = "";
                                        closeProgressDialog();
                                    }

                                }));

                            }


                    });
                    builder.show();
                } else {
                    showToast("竞拍已经结束");
                }

            }
        });

        priase.setOnClickListener(this);
        collect.setOnClickListener(this);
    }


    public void onStart1() {
        if (isFresh) {
            findViewById(R.id.scrollview_wrapping).setVisibility(View.INVISIBLE);
            findViewById(R.id.realod_layout).setVisibility(View.GONE);
        }
        showProgressDialog();
        if (isLogin()) {
            new GetAuctionShow(getUserid(), mItemId, DataCenter.CATID_acution).execute();
        } else {
            new GetAuctionShow(mItemId, DataCenter.CATID_acution).execute();
        }
    }

    public void onSuccess() {

        closeProgressDialog();
        if (isFresh) {
            findViewById(R.id.scrollview_wrapping).setVisibility(View.VISIBLE);
            findViewById(R.id.realod_layout).setVisibility(View.GONE);
            isFresh = false;
        }

        mAuctionDetail = DataCenter.auctionShow;
        if(mAuctionDetail != null){
            if(mAuctionDetail.getPicture().length == 0){
                detailViewPager.setBackgroundResource(R.drawable.ic_default);
            }
        }
        if (mAuctionDetail == null) {
            return;
        }

        findViewById(R.id.scrollview_wrapping).setVisibility(View.VISIBLE);
        findViewById(R.id.realod_layout).setVisibility(View.GONE);
        //八张详情图片
        imageUrlList = mAuctionDetail.getPicture2();
        initViewPage();

        // 设置数据,这里是当前价格
        String product_price = mAuctionDetail.getCurrprice(); //  decimal  integer
        String product_integer = product_price.substring(0, product_price.indexOf("."));
        String product_decimal = product_price.substring(product_price.indexOf("."));
        details_money_integer.setText(product_integer);
        details_money_decimal.setText(product_decimal);

        // 这里是低价
        mTxtMinPricePatDetail.setText(mAuctionDetail.getPrice());
        mTxtTitle.setText(mAuctionDetail.getTitle());
        mTxtPrivcePeople.setText(mAuctionDetail.getPeople() == 0 ? "没有加价人" : mAuctionDetail.getEndbidder());
        mTxtPeopleCount.setText(mAuctionDetail.getPeople() + ""); //加价人数
        mTxtPrivceTimes.setText(mAuctionDetail.getCount());//加价次数
        //倒计时
        //mTxtTime.setText(mAuctionDetail.getEndtime());
        long currentTime = System.currentTimeMillis();
        //end 计算结束时间
        //final long end = start + min * 60 * 1000;
        final long end = (mAuctionDetail.getTotime()) * 1000; // getTotime返回的是秒
        if (currentTime >= end || end == 0) { //表示已经结束
            mTxtTime.setText("竞拍结束");
        } else {
            // setTimer();
            if (isFirst) {
                timer.schedule(task, 0, 1000);       // timeTask
                isFirst = false;
            }
        }
        mTxtPatDetaiContent.setText(mAuctionDetail.getIntroduce());

        if (mAuctionDetail.isIs_praise()) { // 已经点赞过了
            priase.setBackgroundResource(R.drawable.list_collection_block);
            priaseFlag = true;
        } else {
            priase.setBackgroundResource(R.drawable.list_collection_empty);
            priaseFlag = false;
        }

        if (mAuctionDetail.isIs_fav()) { // 已经收藏
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.shoucanged));
            collectFlag = true;
        } else {
            collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
            collectFlag = false;
        }
    }

    public void onFailure() {
        closeProgressDialog();
        showReloadView();
    }

    private void getNetData() {
        onStart1();
    }

//    private void getNetData() {
//
//        RequestParams params = new RequestParams();
//        params.put("itemid", mItemId);
//        if (isLogin()) {
//            params.put("userid", getUserid());
//        }
//        //  catid详情访问是死的
//        params.put("catid", DataCenter.CATID_acution + " ");
//        RequestClient.get(this, "http://www.3tixa.com:8086/kaiyi/group/show.php", params, new AsyncHttpResponseParse(this, new LoadDataHandler() {
//
//            @Override
//            public void onStart() {
//                if (isFresh) {
//                    findViewById(R.id.scrollview_wrapping).setVisibility(View.INVISIBLE);
//                    findViewById(R.id.realod_layout).setVisibility(View.GONE);
//                }
//                showProgressDialog();
//            }
//
//            @Override
//            public void onSuccess(String data) {
//
//                closeProgressDialog();
//                if (isFresh) {
//                    findViewById(R.id.scrollview_wrapping).setVisibility(View.VISIBLE);
//                    findViewById(R.id.realod_layout).setVisibility(View.GONE);
//                    isFresh = false;
//                }
//
//
//                Log.d("log_ktian", data);
//                if (data == null || "".equals(data)) {
//                    return;
//                }
//
//                Gson gson = new Gson();
//                mAuctionDetail = gson.fromJson(data, AuctionDetail.class);
//                Log.d("AuctionDetailActivity", mAuctionDetail.toString());
//                gson = null;
//
//                findViewById(R.id.scrollview_wrapping).setVisibility(View.VISIBLE);
//                findViewById(R.id.realod_layout).setVisibility(View.GONE);
//                //八张详情图片
//                imageUrlList = mAuctionDetail.getPicture2();
//                initViewPage();
//
//                // 设置数据,这里是当前价格
//                String product_price = mAuctionDetail.getCurrprice(); //  decimal  integer
//                String product_integer = product_price.substring(0, product_price.indexOf("."));
//                String product_decimal = product_price.substring(product_price.indexOf("."));
//                details_money_integer.setText(product_integer);
//                details_money_decimal.setText(product_decimal);
//
//                // 这里是低价
//                mTxtMinPricePatDetail.setText(mAuctionDetail.getPrice());
//                mTxtTitle.setText(mAuctionDetail.getTitle());
//                mTxtPrivceTimes.setText(mAuctionDetail.getCount());
//
//                mTxtPrivcePeople.setText(mAuctionDetail.getPeople() == 0 ? "没有加价人" : mAuctionDetail.getEndbidder());
//                mTxtPeopleCount.setText(mAuctionDetail.getPeople() + "");
//                //倒计时
//                //mTxtTime.setText(mAuctionDetail.getEndtime());
//                long currentTime = System.currentTimeMillis();
//                //end 计算结束时间
//                //final long end = start + min * 60 * 1000;
//                final long end = (Long.parseLong(mAuctionDetail.getTotime())) * 1000; // getTotime返回的是秒
//                if (currentTime >= end || end == 0) { //表示已经结束
//                    mTxtTime.setText("竞拍结束");
//                } else {
//                    // setTimer();
//                    if (isFirst) {
//                        timer.schedule(task, 0, 1000);       // timeTask
//                        isFirst = false;
//                    }
//                }
//                mTxtPatDetaiContent.setText(mAuctionDetail.getIntroduce());
//
//                if (mAuctionDetail.isIs_praise()) { // 已经点赞过了
//                    priase.setBackgroundResource(R.drawable.list_collection_block);
//                    priaseFlag = true;
//                } else {
//                    priase.setBackgroundResource(R.drawable.list_collection_empty);
//                    priaseFlag = false;
//                }
//
//                if (mAuctionDetail.isIs_fav()) { // 已经收藏
//                    collect.setBackgroundResource(R.drawable.product_start_stock);
//                    collectFlag = true;
//                } else {
//                    collect.setBackgroundResource(R.drawable.product_start_empty);
//                    collectFlag = false;
//                }
//            }
//
//            @Override
//            public void onFinish() {
//
//            }
//
//            @Override
//            public void onFailure() {
//                super.onFailure();
//                closeProgressDialog();
//                showReloadView();
//            }
//
//
//        }));
//    }

    /**
     * 判断竞拍是否结束
     *
     * @return 结束返回true
     */
    private boolean isEnd() {
        //倒计时
        //mTxtTime.setText(mAuctionDetail.getEndtime());
        long currentTime = System.currentTimeMillis();
        //end 计算结束时间
        //final long end = start + min * 60 * 1000;
        final long end = (mAuctionDetail.getTotime()) * 1000; // getTotime返回的是秒
        if (currentTime >= end || end == 0) { //表示已经结束
            //mTxtTime.setText("竞拍结束");
            return true;
        } else {
            return false;
        }
    }


    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    //show是剩余时间，即要显示的时间
                    final long end = (mAuctionDetail.getTotime()); // getTotime返回的是秒

                    long time = end - System.currentTimeMillis() / 1000;
                    int days = ((int) time) / (3600 * 24);
                    int hours = ((int) time) % (3600 * 24) / 3600;
                    int minutes = ((int) time) % (3600 * 24) % 3600 / 60;
                    int seconds = ((int) time) % (3600 * 24) % 3600 % 60 % 60;

                    mTxtTime.setText(days + "天" + hours + "时" + minutes + "分" + seconds + "秒");
                    if (time <= 0) {
                        timer.cancel();
                        mTxtTime.setText("竞拍结束");
                    }
            }
        }
    };

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };

    @Override
    public void onClick(View v) {

        if (!HttpUtils.isConnected()) {
            showToast("离线模式，无法操作，请连接网络");
            return;
        }

        if (mAuctionDetail == null) {
            showToast("详情加载失败");
            return;
        }
        if (!isLogin()) {
            startLoginOrRegistered();
            return;
        }


        String userid = DataCenter.userLogin.get(0).getUserid();

        switch (v.getId()) {
            case R.id.daydaycoupon_product_favorite: //收藏，或者关注
                String action = "add";
                if (collectFlag) {
                    action = "delete";
                }
                showProgressDialog();
                new PostAddFavorites(DataCenter.CATID_acution, userid, action, mAuctionDetail.getItemid(), mAuctionDetail.getTitle()).execute();
                break;
            case R.id.daydaycoupon_product_fav: //点赞
                String actions = "add";// 没有点赞
                if (priaseFlag) {
                    actions = "delete";
                }
                showProgressDialog();
                new PostPraise(DataCenter.CATID_acution, getUserid(), mAuctionDetail.getItemid(), actions).execute();
                break;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        DataCenter.flag flag = (DataCenter.flag) data;
        closeProgressDialog();

        if (flag == DataCenter.flag.POST_PRAISE_SUCESS) { //点赞成功
            if (DataCenter.code.equals(DataCenter.successFlag)) {
                if (priaseFlag) {//从当前的点赞状态变成没有点赞
                    priaseFlag = false;
                    // title = "取消点赞";
                    showToast(getString(R.string.praise_cancle));
                    priase.setBackgroundResource(R.drawable.list_collection_empty);
                } else {
                    //title = "点赞成功";
                    showToast(getString(R.string.praise_add));
                    priaseFlag = true;
                    priase.setBackgroundResource(R.drawable.list_collection_block);
                }
            } else {
                showToast(DataCenter.msg, "点赞出现错误");
            }
        }

        if (flag == DataCenter.flag.GetAddMESSAGEINFO_SUCCESS) {//收藏成功,关注成功\
            if (DataCenter.successFlag.equals(DataCenter.code)) {
                if (collectFlag) {//从当前的关注状态变成没有关注
                    collectFlag = false;
                    //msg = "取消收藏";
                    showToast(getString(R.string.collect_cancle));
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucang));
                } else {
                    collectFlag = true;
                    collect.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.shoucanged));
                    //msg = "收藏成功";
                    showToast(getString(R.string.collect_add));
                }
            } else {
                showToast(DataCenter.msg, "收藏出现错误");
            }
        }

        if (flag == DataCenter.flag.GET_AUCTION_SHOW_SUCCESS) { //详情页面数据获取成功

            onSuccess();
        } else if(flag == DataCenter.flag.GET_AUCTION_SHOW_FAILED) {
            onFailure();
        }
    }

}
